package com.hopechart.micro.common.generator.service;

import com.hopechart.micro.common.exception.BusinessException;
import com.hopechart.micro.common.exception.ErrorCode;
import com.hopechart.micro.common.generator.AbstractGenerator;
import com.hopechart.micro.util.StringUtil;
import freemarker.template.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.util.Map;

/**
 * @author daijiang@hopechart.com
 */
public class ServiceGenerator extends AbstractGenerator {

    private static final Logger logger = LoggerFactory.getLogger(ServiceGenerator.class);

    @Override
    public void executor(String tableName, String modelName) {
        Configuration cfg = getFreemarkerConfiguration();
        String modelNameUpperCamel;

        if(StringUtil.isEmpty(modelName)) {
            // USER_NAME to UserName
            modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
            modelName = modelNameUpperCamel;
        } else {
            modelNameUpperCamel = modelName;
        }

        Map<String, Object> data = getTemplateParam(tableName, modelName);
        try {
            // 创建 Service 接口
            String serviceFilePath = getServiceSavePath() + "I" + modelNameUpperCamel + "Service.java";
            File serviceFile = new File(serviceFilePath);
            // 查看父级目录是否存在, 不存在则创建
            if (!serviceFile.getParentFile().exists()) {
                serviceFile.getParentFile().mkdirs();
            }
            cfg.getTemplate("service.ftl").process(data, new FileWriter(serviceFile));
            logger.info("I" + modelNameUpperCamel + "Service.java 生成成功.");

            // 创建 Service 接口的实现类
            File serviceImplFile = new File(getServiceImplSavePath() +
                    modelNameUpperCamel + "ServiceImpl.java");
            // 查看父级目录是否存在, 不存在则创建
            if (!serviceImplFile.getParentFile().exists()) {
                serviceImplFile.getParentFile().mkdirs();
            }
            cfg.getTemplate("service-impl.ftl").process(data, new FileWriter(serviceImplFile));
            logger.info(modelNameUpperCamel + "ServiceImpl.java 生成成功.");
        } catch (Exception e) {
            logger.error("业务层代码生成异常，{}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.GEN_SERVICE, "业务层代码生成异常，{" + e.getMessage() + "}", e);
        }
    }
}
